# Config
import thread
import os
from socket import *
import time

class ChatServer:
	clientFeedbackFreq 		= 1
	wdSendFreq 					= 0.5
	listenPort					= 23000
	sendPort						= listenPort+1

	# INIT
	
	shutdown = 0
	restart 	= 0
	#commandA = {}
	clientsA = {}
	oldClientsA = {}
	
	def __init__(self,parent):
		self.parent = parent
		#self.commandA["SPEED"] = 0
		#self.commandA["DIR"]	= 0
		#self.commandA["RAMP"] 	= "off"
		

	

	# Setting up for start
	

	def checkClients(self):
		while(1):
			#print "Checking for dead clients"
			for key in self.clientsA.keys():
				if self.clientsA[key] != self.oldClientsA[key]:
					#everything is ok
					self.oldClientsA[key]=self.clientsA[key]
				else:
					# no change for 1 minute, kill the client
					self.msg(key+" has been disconnected by server [TIMEOUT]")
					del self.clientsA[key]
					del self.oldClientsA[key]
					if (len(self.clientsA)<=0):
						self.parent.parseCommand("noclients")
			time.sleep(10)


	def ack(self,message):
		for val in self.clientsA.keys():
			addr = (str(val),self.sendPort)
			UDPSock = socket(AF_INET,SOCK_DGRAM)
			UDPSock.sendto(message,addr)


			
	def msg(self,message):
		self.ack(message)
		print message
			
	def wdWriter(self):
		n=0
		while(1):
			if n>99:
				n=0
			self.ack("SWD:"+str(n))
			n=n+1
			time.sleep(1/self.wdSendFreq)

	def clientFeedback(self):
		while(1):
			#ack("FB")
			for key,val in self.parent.commandA.items():
				self.ack(str(key)+"="+str(val))
			time.sleep(1/self.clientFeedbackFreq)

	def udpListener(self):
		host = ''
		port = self.listenPort
		buf = 1024
		addr = (host,port)
		UDPSock = socket(AF_INET,SOCK_DGRAM)
		UDPSock.bind(addr)

		while(1):
			data,addr = UDPSock.recvfrom(buf)
			try:
				self.clientsA[addr[0]]=self.clientsA[addr[0]]+1
			except:
				print "Connection from new client "+addr[0]+", ADDING"
				self.clientsA[addr[0]]=1
				self.oldClientsA[addr[0]]=0
			self.parent.parseCommand(data)
		
			
	def console(self):
		print "Starting Console"
		
		while(1):
			cmd = raw_input("> ")
			self.parent.parseCommand(cmd)
			
			

	def main(self):
		wdThread 				= thread.start_new_thread(self.wdWriter,())
		udpListenerThread 	= thread.start_new_thread(self.udpListener,())
		consoleThread 			= thread.start_new_thread(self.console,())
		clientFeedbackThread = thread.start_new_thread(self.clientFeedback,())
		checkClientsThread	= thread.start_new_thread(self.checkClients,())
	
	#if __name__=="__main__":
	#	main(1)



	#sys.stdout.write(line)